package com.mikey.bq;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author :Mikey
 * @description :同步对列 和其他BlockingQueue不一样，只能存一个元素，取出之后才能存
 * @create :2022-09-21 16:24:00
 */
public class SynchronousQueueDemo {
    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new SynchronousQueue();
        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName()+"put 1");
                blockingQueue.put("1");
                System.out.println(Thread.currentThread().getName()+"put 2");
                blockingQueue.put("2");
                System.out.println(Thread.currentThread().getName()+"put 3");
                blockingQueue.put("3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"A").start();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(3);
                blockingQueue.take();
                System.out.println(Thread.currentThread().getName()+"take 1");
                TimeUnit.SECONDS.sleep(3);
                blockingQueue.take();
                System.out.println(Thread.currentThread().getName()+"take 2");
                TimeUnit.SECONDS.sleep(3);
                blockingQueue.take();
                System.out.println(Thread.currentThread().getName()+"take 3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"B").start();
    }
}
